using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using ECommerce.Library;
using System.Collections.Generic;
using Ext.Net;
using Entity;
using System.Text;

public partial class admin_sales_ccsuccess : SiteAdminBasePage
{
    private bool _useSearch
    {
        get
        {
            if (Session["_useSearch"] == null)
                return false;
            else return Convert.ToBoolean(Session["_useSearch"]);
        }
        set
        {
            Session["_useSearch"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        uccResponseMessage.Visible = false;
        if (!X.IsAjaxRequest)
        {
            Session["_useSearch"] = null;
            Session["PrintOrderList"] = null;
        }
    }

    protected void Store1_RefreshData(object sender, StoreRefreshDataEventArgs e)
    {
        BindOrders(e.Sort + (e.Dir.ToString() == "Default" ? "" : " " + e.Dir), e.Start, e.Limit);
      
    }

    private void BindOrders(string sort, int start, int limit)
    {
        ReadWriteCustomCollection<ProductPurchaseOrder> data = null;
        int totalCount = 0;
        string sqlCondition = string.Empty;
        sqlCondition += "(OrderStatus ='CCSuccess'  OR  OrderStatus ='ManualAuthorization' )";
       // start = start * limit;
        if (String.IsNullOrEmpty(sort))
            sort = "OrderId desc";
        
        double fromPrice = 0;
        Double.TryParse(txtPriceFrom.Text, out fromPrice);

        double toPrice = 0;
        Double.TryParse(txtPriceTo.Text, out toPrice);

        if (this._useSearch)
        {
            if (!string.IsNullOrEmpty(txtOrderNo.Text)) 
            {
                sqlCondition += " AND OrderCode='"+txtOrderNo.Text.ToString()+"'";
            }
            if (!string.IsNullOrEmpty(txtLastName.Text))
            {
                sqlCondition += " AND BillingLastName LIKE '%" + txtLastName.Text + "%'";
            }
            //if (!string.IsNullOrEmpty(txtCustomerNo.Text))
            //{
            //    sqlCondition += " AND UserId=" + txtOrderNo.Text;
            //}
            if (txtDateFrom.SelectedDate > DateTime.MinValue)
            {
                sqlCondition += " AND CreateDate>='" + ECommerce.Library.ECommerce.Utility.FormatDateTime(txtDateFrom.SelectedDate, '-') + "'";
            }
            if (txtDateTo.SelectedDate > DateTime.MinValue)
            {
                sqlCondition += " AND CreateDate<='" + ECommerce.Library.ECommerce.Utility.FormatDateTime(txtDateTo.SelectedDate, '-') + "'";
            }

            if (fromPrice > 0.0)
            {
                sqlCondition += " AND OrderPrice>=" + fromPrice.ToString();
            }
            if (toPrice > 0.0)
            {
                sqlCondition += " AND OrderPrice<=" + toPrice.ToString();
            }

            if (!string.IsNullOrEmpty(txtFirstName.Text))
            {
                sqlCondition += " AND BillingFirstName LIKE '%" + txtFirstName.Text + "%'";
            }

            if (!string.IsNullOrEmpty(txtEmail.Text))
            {
                sqlCondition += " AND BillingEmailAddress LIKE '%" + txtEmail.Text + "%'";
            }
            if (Session["ShippedFilter"] != null)
            {
                sqlCondition += " AND ShippingStatus='Shipped'";
                Session["ShippedFilter"] = null;
            }
            if (Session["UnprocessedFilter"] != null)
            {
                sqlCondition += " AND OrderTrackNumber='' AND  PrintNo <= 0 OR PrintNo is null";
                Session["UnprocessedFilter"] = null;
            }
            if (Session["PrintFilter"] != null)
            {
                sqlCondition += " AND PrintNo > 0";
                Session["PrintFilter"] = null;
            }
            if (Session["GiftMessage"] != null)
            {
                sqlCondition += " AND len(GIftCardMessage)>1";
                Session["GiftMessage"] = null;
            }


            this._useSearch = false;
        }

        data = ProductPurchaseOrder.GetBackendProductPurchaseOrderListByCondition(sqlCondition, sort, start, limit);

        RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
        for (int i = 0; i < data.Count; i++)
        {
            if (!string.IsNullOrEmpty(data[i].GIftCardMessage))
            {
                sm.SelectedRow = new SelectedRow(i);
                sm.SelectedRows.Add(new SelectedRow(i));
            }
        }

        totalCount = ProductPurchaseOrder.GetBackendProductPurchaseOrderListByConditionCount(sqlCondition);
        Store1.DataSource = data;
        Store1.DataBind();
        //RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
        //sm.Style.Add("color", "red");
        //sm.SelectedRows.Add(new SelectedRow(2));
        
        
        (Store1.Proxy[0] as PageProxy).Total = totalCount;
    }

    [DirectMethod(Namespace = "Polana.WebService")]
    public void UpdateOrder(int id, string trackingNumber)
    {
        trackingNumber = trackingNumber.Trim();
        ProductPurchaseOrder productPurchaseOrder = ProductPurchaseOrder.Load(id);

        if (!string.IsNullOrEmpty(trackingNumber))
        {
            try
            {
                productPurchaseOrder.OrderTrackNumber = trackingNumber;

                //// Send mail to customer with link to track shipment
                //TemplateHelper th = new TemplateHelper(
                //                            TemplateHelper.LoadUserControl("~/controls/email-templates/ProductTracking.ascx"));
                //th.SetValue("OrderNumber", productPurchaseOrder.OrderNumber);
                //th.SetValue("TrackingNumber", productPurchaseOrder.OrderTrackNumber);
                //th.SetValue("CustomerName", productPurchaseOrder.BillingAddress.FirstName + " " + productPurchaseOrder.BillingAddress.LastName);
                //if (Email.SendGenericEmail(productPurchaseOrder.BillingAddress.FirstName + " " + productPurchaseOrder.BillingAddress.LastName, productPurchaseOrder.BillingAddress.EmailAddress, "Your order has been shipped", th.GetTemplateContent()))
                //{
                    productPurchaseOrder.Update();
                    //X.MessageBox.Notify("Success", "Tracking number sent successfully.");
                //}
                //else
                //    X.MessageBox.Notify("Failure", "Tracking number could not be sent. Please try again.");

                
            }
            catch
            {
                X.MessageBox.Notify("Failure", "Tracking number could not be sent. Please try again.");
            }
        }
    }

    [DirectMethod(Namespace = "Polana.WebService")]
    public void DeleteOrders(string ids)
    {
        ids = ids.TrimStart(' ');
        string[] idArray = ids.Split(' ');
        List<int> idList = new List<int>();
        foreach (string id in idArray)
        {
            TblProductPurchaseOrder order = TblProductPurchaseOrder.GetTblProductPurchaseOrderByOrderId(Convert.ToInt32(id));
            if (order.GiftCertificateId != null)
            {
                if(order.GiftCertificateId>0)
                TblGiftCertificate.DeleteTblGiftCertificate(order.GiftCertificateId);
            }
            TblProductPurchaseOrder_MultipleShippingInfo_Extended.DeleteTblProductPurchaseOrder_MultipleShippingInfo(order.OrderId);
            TblProductPurchaseOrder.DeleteTblProductPurchaseOrder(order.OrderId);
        }
        Store1.DataBind();
        //idList.Add(Convert.ToInt32(id));
        //ProductPurchaseOrder.DeleteProductPurchaseOrder(idList);
    }

    [DirectMethod(Namespace = "Polana.WebService")]
    public void SearchOrder()
    {
        _useSearch = true;
        Store1.DataBind();
    }

    [DirectMethod(Namespace = "Polana.WebService")]
    public void PrintOrders(string ids)
    { 
       ids = ids.TrimStart(' ');
       string[] idArray = ids.Split(' ');
       List<string> idList = new List<string>();
       foreach (string id in idArray)
       {
           idList.Add(Convert.ToString(id));
       }
        Session["PrintOrderList"] = idList;
        Response.Redirect("~/invoice-quick-print.aspx");
       // Response.Redirect("~/admin/quick-print.aspx");
    }
    [DirectMethod(Namespace = "Polana.WebService")]
    public void QuickOrders() 
    {
        _useSearch = true;
        Store1.DataBind();
    }

    [DirectMethod(Namespace = "Polana.WebService")]
    public void PrintFilter()
    {
        Session["PrintFilter"] = "Print";
        _useSearch = true;
        Store1.DataBind();
    }
    [DirectMethod(Namespace = "Polana.WebService")]
    public void ShippedFilter()
    {
        Session["ShippedFilter"] = "Shipped";
        _useSearch = true;
        Store1.DataBind();
    }
    [DirectMethod(Namespace = "Polana.WebService")]
    public void UnprocessedFilter()
    {
        Session["UnprocessedFilter"] = "UnprocessedFilter";
        _useSearch = true;
        Store1.DataBind();
    }
    [DirectMethod(Namespace = "Polana.WebService")]
    public void GiftMessage()
    {
        Session["GiftMessage"] = "GiftMessage";
        _useSearch = true;
        Store1.DataBind();
    }
}


